'use client';

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Select, 
  Button, 
  Table, 
  Space, 
  Tag, 
  Modal, 
  message, 
  Row, 
  Col, 
  Divider,
  Typography,
  Badge,
  Tooltip,
  Popconfirm,
  Upload,
  InputNumber,
  Switch,
  Tabs
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  UploadOutlined,
  DownloadOutlined,
  ClearOutlined,
  EyeOutlined,
  CopyOutlined
} from '@ant-design/icons';
import { SDTemplate, TemplateType } from '@/types/templates';
import styles from './page.module.scss';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  total?: number;
  page?: number;
  pageSize?: number;
}

const ModelRegistrationPage: React.FC = () => {
  const [form] = Form.useForm();
  const [templates, setTemplates] = useState<SDTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<SDTemplate | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<TemplateType | 'all'>('all');
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [viewingTemplate, setViewingTemplate] = useState<SDTemplate | null>(null);
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string>('');

  // 处理图片上传
  const handleImageUpload = (info: any) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // 上传成功，设置图片URL
      const imageUrl = info.file.response?.url;
      if (imageUrl) {
        setUploadedImageUrl(imageUrl);
        // 直接将上传后的图片路径填入输入框
        form.setFieldsValue({ image: imageUrl });
        message.success('图片上传成功，路径已自动填入');
      }
    } else if (info.file.status === 'error') {
      message.error('图片上传失败');
    }
  };

  // 上传前验证
  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过5MB!');
      return false;
    }
    return true;
  };

  // 获取模板列表
  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/templates-db');
      const result: ApiResponse<SDTemplate[]> = await response.json();
      
      if (result.success && result.data) {
        setTemplates(result.data);
        message.success(`成功加载 ${result.data.length} 个模板`);
      } else {
        message.error(`加载失败: ${result.error}`);
      }
    } catch (error: any) {
      message.error(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 创建或更新模板
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const templateData = {
        ...values,
        image: values.image?.startsWith('/') ? values.image : `/${values.image}`,
      };

      const url = editingTemplate 
        ? `/api/templates-db/${editingTemplate.id}`
        : '/api/templates-db';
      
      const method = editingTemplate ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ template: templateData })
      });

      const result: ApiResponse<SDTemplate> = await response.json();
      
      if (result.success) {
        message.success(`模板${editingTemplate ? '更新' : '创建'}成功`);
        setModalVisible(false);
        setEditingTemplate(null);
        form.resetFields();
        await fetchTemplates();
      } else {
        message.error(`${editingTemplate ? '更新' : '创建'}失败: ${result.error}`);
      }
    } catch (error: any) {
      message.error(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 删除模板
  const handleDelete = async (id: string, name: string) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/templates-db/${id}`, {
        method: 'DELETE'
      });

      const result = await response.json();
      
      if (result.success) {
        message.success(`模板 "${name}" 删除成功`);
        await fetchTemplates();
      } else {
        message.error(`删除失败: ${result.error}`);
      }
    } catch (error: any) {
      message.error(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的模板');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/templates-db', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ ids: selectedRowKeys.join(',') })
      });

      const result = await response.json();
      
      if (result.success) {
        message.success(`成功删除 ${selectedRowKeys.length} 个模板`);
        setSelectedRowKeys([]);
        await fetchTemplates();
      } else {
        message.error(`批量删除失败: ${result.error}`);
      }
    } catch (error: any) {
      message.error(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 复制模板
  const handleCopy = (template: SDTemplate) => {
    const { id, created_at, updated_at, ...templateData } = template;
    form.setFieldsValue({
      ...templateData,
      name: `${template.name} (副本)`
    });
    setEditingTemplate(null);
    setModalVisible(true);
  };

  // 编辑模板
  const handleEdit = (template: SDTemplate) => {
    const { id, created_at, updated_at, ...templateData } = template;
    form.setFieldsValue(templateData);
    setEditingTemplate(template);
    setUploadedImageUrl(template.image || '');
    setModalVisible(true);
  };

  // 查看模板详情
  const handleView = (template: SDTemplate) => {
    setViewingTemplate(template);
    setViewModalVisible(true);
  };

  // 过滤模板
  const filteredTemplates = templates.filter(template => {
    const matchesSearch = template.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         template.description.toLowerCase().includes(searchText.toLowerCase());
    const matchesType = filterType === 'all' || template.type === filterType;
    return matchesSearch && matchesType;
  });

  // 表格列定义
  const columns = [
    {
      title: '预览',
      dataIndex: 'image',
      key: 'image',
      width: 65,
      render: (imageUrl: string) => (
        imageUrl ? (
          <img 
            src={imageUrl} 
            alt="预览" 
            style={{ 
              width: '45px', 
              height: '45px', 
              objectFit: 'cover',
              borderRadius: '4px',
              border: '1px solid #333'
            }} 
          />
        ) : (
          <div style={{ 
            width: '45px', 
            height: '45px', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            backgroundColor: '#2a2a2a',
            borderRadius: '4px',
            border: '1px solid #333',
            color: '#666',
            fontSize: '12px'
          }}>
            无
          </div>
        )
      ),
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      ellipsis: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: TemplateType) => {
        const colors = {
          txt2img: 'blue',
          img2img: 'green',
          postprocess: 'orange'
        };
        return <Tag color={colors[type]}>{type}</Tag>;
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '基础模型',
      dataIndex: 'base_model',
      key: 'base_model',
      width: 180,
      ellipsis: true,
      render: (text: string) => text || '-'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (text: string) => text ? new Date(text).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record: SDTemplate) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleView(record)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button 
              type="text" 
              icon={<CopyOutlined />} 
              onClick={() => handleCopy(record)}
              size="small"
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个模板吗？"
            onConfirm={() => handleDelete(record.id, record.name)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                danger
                size="small"
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 页面加载时获取数据
  useEffect(() => {
    fetchTemplates();
  }, []);

  return (
    <div className={styles.container}>
      {/* 页面头部 */}
      <div className={styles.header}>
        <div className={styles.headerContent}>
          <div className={styles.headerLeft}>
            <Title level={2} className={styles.title}>模型注册管理</Title>
            <Badge count={templates.length} showZero color="#00ff00" />
          </div>
          <div className={styles.headerRight}>
            <Space>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={fetchTemplates}
                loading={loading}
              >
                刷新
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={() => {
                  form.resetFields();
                  setEditingTemplate(null);
                  setModalVisible(true);
                }}
              >
                新建模板
              </Button>
            </Space>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className={styles.content}>
        <Card className={styles.mainCard}>
          {/* 搜索和过滤 */}
          <div className={styles.filterSection}>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <Input
                  placeholder="搜索模板名称或描述..."
                  prefix={<SearchOutlined />}
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  allowClear
                />
              </Col>
              <Col>
                <Select
                  value={filterType}
                  onChange={setFilterType}
                  style={{ width: 150 }}
                >
                  <Option value="all">全部类型</Option>
                  <Option value="txt2img">Text to Image</Option>
                  <Option value="img2img">Image to Image</Option>
                  <Option value="postprocess">Post Process</Option>
                </Select>
              </Col>
              <Col>
                <Popconfirm
                  title="确定要删除选中的模板吗？"
                  onConfirm={handleBatchDelete}
                  disabled={selectedRowKeys.length === 0}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    danger
                    icon={<DeleteOutlined />}
                    disabled={selectedRowKeys.length === 0}
                  >
                    批量删除 ({selectedRowKeys.length})
                  </Button>
                </Popconfirm>
              </Col>
            </Row>
          </div>

          <Divider />

          {/* 数据表格 */}
          <Table
            columns={columns}
            dataSource={filteredTemplates}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }}
            rowSelection={{
              selectedRowKeys,
              onChange: (selectedRowKeys: React.Key[]) => {
                setSelectedRowKeys(selectedRowKeys.map(key => String(key)));
              },
              preserveSelectedRowKeys: true
            }}
            scroll={{ x: 1200 }}
          />
        </Card>
      </div>

      {/* 创建/编辑模板对话框 */}
      <Modal
        title={editingTemplate ? '编辑模板' : '创建模板'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingTemplate(null);
          form.resetFields();
        }}
        footer={null}
        width={800}
        className={styles.modal}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            type: 'txt2img',
            sampler_name: 'DPM++ 2M Karras',
            steps: 20,
            cfg_scale: 7.0,
            width: 1024,
            height: 1024,
            seed: -1,
            lora_weight: 0.8,
            batch_count: 1,
            batch_size: 1,
            denoising_strength: 0.75,
            upscaling_resize: 2,
            upscaler_1: 'R-ESRGAN 4x+',
            upscaler_2: 'None',
            extras_upscaler_2_visibility: 0
          }}
        >
          <Tabs defaultActiveKey="basic">
            <TabPane tab="基础信息" key="basic">
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="name"
                    label="模板名称"
                    rules={[{ required: true, message: '请输入模板名称' }]}
                  >
                    <Input placeholder="请输入模板名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="type"
                    label="模板类型"
                    rules={[{ required: true, message: '请选择模板类型' }]}
                  >
                    <Select>
                      <Option value="txt2img">Text to Image</Option>
                      <Option value="img2img">Image to Image</Option>
                      <Option value="postprocess">Post Process</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="description"
                label="描述"
              >
                <TextArea rows={3} placeholder="请输入模板描述" />
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="image"
                    label="预览图片"
                    rules={[{ required: true, message: '请上传预览图片' }]}
                  >
                    <Upload
                        name="image"
                        action="/api/upload"
                        listType="picture-card"
                        className={styles.imageUploader}
                        showUploadList={false}
                        beforeUpload={beforeUpload}
                        onChange={handleImageUpload}
                      >
                      {uploadedImageUrl || form.getFieldValue('image') ? (
                        <img 
                          src={uploadedImageUrl || form.getFieldValue('image')} 
                          alt="预览" 
                          style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                        />
                      ) : (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>上传图片</div>
                        </div>
                      )}
                    </Upload>
                    <Input 
                      placeholder="或直接输入图片路径" 
                      style={{ marginTop: 8 }}
                      value={uploadedImageUrl || form.getFieldValue('image') || ''}
                      onChange={(e) => {
                        setUploadedImageUrl(e.target.value);
                        form.setFieldsValue({ image: e.target.value });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="base_model"
                    label="基础模型"
                    rules={[{ required: true, message: '请输入基础模型' }]}
                  >
                    <Input placeholder="sd_xl_base_1.0.safetensors" />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab="模型配置" key="model">
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item name="lora_model" label="LORA模型">
                    <Input placeholder="lora_model.safetensors" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="lora_output_name" label="LORA输出名称">
                    <Input placeholder="lora输出名称" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item name="lora_weight" label="LORA权重">
                    <InputNumber min={0} max={2} step={0.1} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="vae" label="VAE模型">
                    <Input placeholder="vae模型文件" />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab="生成参数" key="generation">
              <Form.Item
                name="prompt"
                label="正向提示词"
                rules={[{ required: true, message: '请输入正向提示词' }]}
              >
                <TextArea rows={4} placeholder="描述你想要生成的图像..." />
              </Form.Item>

              <Form.Item name="negative_prompt" label="负向提示词">
                <TextArea rows={3} placeholder="描述你不想要的元素..." />
              </Form.Item>

              <Row gutter={16}>
                <Col span={8}>
                  <Form.Item name="sampler_name" label="采样器">
                    <Select>
                      <Option value="DPM++ 2M Karras">DPM++ 2M Karras</Option>
                      <Option value="Euler a">Euler a</Option>
                      <Option value="DDIM">DDIM</Option>
                      <Option value="DPM++ SDE Karras">DPM++ SDE Karras</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="steps" label="步数">
                    <InputNumber min={1} max={150} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="cfg_scale" label="CFG Scale">
                    <InputNumber min={1} max={30} step={0.5} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={8}>
                  <Form.Item name="width" label="宽度">
                    <InputNumber min={64} max={2048} step={64} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="height" label="高度">
                    <InputNumber min={64} max={2048} step={64} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="seed" label="随机种子">
                    <InputNumber style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
                {({ getFieldValue }) => {
                  const type = getFieldValue('type');
                  
                  if (type === 'img2img') {
                    return (
                      <Form.Item name="denoising_strength" label="去噪强度">
                        <InputNumber min={0} max={1} step={0.05} style={{ width: '100%' }} />
                      </Form.Item>
                    );
                  }
                  
                  if (type === 'postprocess') {
                    return (
                      <>
                        <Row gutter={16}>
                          <Col span={12}>
                            <Form.Item name="upscaling_resize" label="放大倍数">
                              <InputNumber min={1} max={8} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item name="upscaler_1" label="放大器1">
                              <Select>
                                <Option value="R-ESRGAN 4x+">R-ESRGAN 4x+</Option>
                                <Option value="ESRGAN_4x">ESRGAN_4x</Option>
                                <Option value="SwinIR_4x">SwinIR_4x</Option>
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={16}>
                          <Col span={12}>
                            <Form.Item name="upscaler_2" label="放大器2">
                              <Select>
                                <Option value="None">None</Option>
                                <Option value="R-ESRGAN 4x+">R-ESRGAN 4x+</Option>
                                <Option value="ESRGAN_4x">ESRGAN_4x</Option>
                              </Select>
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item name="extras_upscaler_2_visibility" label="放大器2可见性">
                              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                        </Row>
                      </>
                    );
                  }
                  
                  return null;
                }}
              </Form.Item>
            </TabPane>
          </Tabs>

          <Divider />
          
          <div className={styles.modalFooter}>
            <Space>
              <Button onClick={() => {
                setModalVisible(false);
                setEditingTemplate(null);
                setUploadedImageUrl('');
                form.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                {editingTemplate ? '更新' : '创建'}
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>

      {/* 查看模板详情对话框 */}
      <Modal
        title="模板详情"
        open={viewModalVisible}
        onCancel={() => {
          setViewModalVisible(false);
          setViewingTemplate(null);
        }}
        footer={[
          <Button key="close" onClick={() => {
            setViewModalVisible(false);
            setViewingTemplate(null);
          }}>
            关闭
          </Button>
        ]}
        width={600}
        className={styles.modal}
      >
        {viewingTemplate && (
          <div className={styles.templateDetail}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Title level={4}>{viewingTemplate.name}</Title>
                <Tag color={viewingTemplate.type === 'txt2img' ? 'blue' : viewingTemplate.type === 'img2img' ? 'green' : 'orange'}>
                  {viewingTemplate.type}
                </Tag>
              </Col>
              <Col span={24}>
                <Text strong>描述：</Text>
                <br />
                <Text>{viewingTemplate.description || '无描述'}</Text>
              </Col>
              <Col span={12}>
                <Text strong>基础模型：</Text>
                <br />
                <Text code>{(viewingTemplate as any).base_model || '-'}</Text>
              </Col>
              <Col span={12}>
                <Text strong>图片路径：</Text>
                <br />
                <Text code>{viewingTemplate.image}</Text>
              </Col>
              {(viewingTemplate as any).lora_model && (
                <Col span={12}>
                  <Text strong>LORA模型：</Text>
                  <br />
                  <Text code>{(viewingTemplate as any).lora_model}</Text>
                </Col>
              )}
              {(viewingTemplate as any).lora_weight && (
                <Col span={12}>
                  <Text strong>LORA权重：</Text>
                  <br />
                  <Text>{(viewingTemplate as any).lora_weight}</Text>
                </Col>
              )}
              <Col span={24}>
                <Text strong>正向提示词：</Text>
                <br />
                <Text code style={{ whiteSpace: 'pre-wrap' }}>{(viewingTemplate as any).prompt || '-'}</Text>
              </Col>
              {(viewingTemplate as any).negative_prompt && (
                <Col span={24}>
                  <Text strong>负向提示词：</Text>
                  <br />
                  <Text code style={{ whiteSpace: 'pre-wrap' }}>{(viewingTemplate as any).negative_prompt}</Text>
                </Col>
              )}
              <Col span={8}>
                <Text strong>采样器：</Text>
                <br />
                <Text>{(viewingTemplate as any).sampler_name || '-'}</Text>
              </Col>
              <Col span={8}>
                <Text strong>步数：</Text>
                <br />
                <Text>{(viewingTemplate as any).steps || '-'}</Text>
              </Col>
              <Col span={8}>
                <Text strong>CFG Scale：</Text>
                <br />
                <Text>{(viewingTemplate as any).cfg_scale || '-'}</Text>
              </Col>
              <Col span={8}>
                <Text strong>尺寸：</Text>
                <br />
                <Text>{(viewingTemplate as any).width || '-'} × {(viewingTemplate as any).height || '-'}</Text>
              </Col>
              <Col span={8}>
                <Text strong>创建时间：</Text>
                <br />
                <Text>{viewingTemplate.created_at ? new Date(viewingTemplate.created_at).toLocaleString() : '-'}</Text>
              </Col>
              <Col span={8}>
                <Text strong>更新时间：</Text>
                <br />
                <Text>{viewingTemplate.updated_at ? new Date(viewingTemplate.updated_at).toLocaleString() : '-'}</Text>
              </Col>
            </Row>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ModelRegistrationPage;